package java学习.第17章_反射机制;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class G1_反射获取构造器 {
    @Test
    public void 反射获取运行时类() throws
            InstantiationException,
            IllegalAccessException, NoSuchMethodException, InvocationTargetException {

        System.out.println("******newInstance()*********************");
        Class<FS> cla = FS.class;
        //调用空参构造器  9 开始已经不推荐使用了
//        FS f = cla.newInstance();
        //推荐使用这个
        FS f = cla.getDeclaredConstructor().newInstance();

        System.out.println("******getConstructors()*********************");
        Class<FS> fsClass = FS.class;
        System.out.println("***获取运行实例中public构造器*****如下**************************");
        Constructor<?>[] constructors = fsClass.getConstructors();
        for (Constructor c:constructors){
            System.out.println(c);
        }
        System.out.println("***获取运行实例中所有构造器(包括私有的)*****如下**************************");
        Constructor<?>[] declaredConstructors = fsClass.getDeclaredConstructors();
        for (Constructor c:declaredConstructors){
            System.out.println(c);
        }
    }
    @Test
    public void 反射获取构造器() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<FS> cla = FS.class;
        //private FS(String name, int age)
        Constructor<FS> fsCon = cla.getDeclaredConstructor(String.class, int.class);
        fsCon.setAccessible(true);//确保私有构造器可访问
        FS fs = fsCon.newInstance("私有", 66);//调用此构造器
        System.out.println(fs);
    }
}
